package com.lw.ssm.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lw.ssm.cache.CourseCache;
import com.lw.ssm.event.CourseEvent;
import com.lw.ssm.exceptions.MyBaseException;
import com.lw.ssm.mapper.CourseMapper;
import com.lw.ssm.pojo.Course;
import com.lw.ssm.service.CourseService;
import com.lw.ssm.utils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/10 17:00
 */
@Service
@Transactional
public class CourseServiceImpl implements CourseService {

    private CourseMapper courseMapper;

    private CourseCache courseCache;

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setCourseCache(CourseCache courseCache) {
        this.courseCache = courseCache;
    }

    @Autowired
    public void setCourseMapper(CourseMapper courseMapper) {
        this.courseMapper = courseMapper;
    }

    @Override
    public Course findById(Long id) {
        return courseMapper.findById(id);
    }

    @Override
    public PageInfo<Course> findAll(int pageNum,int pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Course> allDate = courseCache.getAllDate();
        List<Course> courseList = allDate.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        PageInfo<Course> pageInfo = new PageInfo<>(courseList);
        pageInfo.setTotal(allDate.size());
        return pageInfo;
    }

    @Override
    public void addCourse(Course course) {
        Assert.isTrue(!course.isEmpty(),()->{
            throw new MyBaseException("数据不能为空", ResultCode.DATA_EMPTY);
        });
        courseMapper.addCourse(course);
        context.publishEvent(new CourseEvent());
    }

    @Override
    public void updateCourse(Course course) {
        courseMapper.updateCourse(course);
        context.publishEvent(new CourseEvent());
    }

    @Override
    public void deleteCourse(Long id) {
        courseMapper.deleteCourse(id);
        context.publishEvent(new CourseEvent());
    }
}
